<template>
    <div class="box">
        <div class="headerContent">
            <!-- <div style="margin-right: 20px" class="headerTitel">打印预览</div> -->
            <el-button :loading="waitShowPrinter" type="primary" icon="printer" @click="print">打印</el-button>
            <el-button type="primary" icon="printer" @click="toPdf">pdf</el-button>
        </div>
        <div id="preview_content_design"></div>
    </div>
</template>
<script>
import { hiprint, defaultElementTypeProvider } from "vue-plugin-hiprint";
import panel from './panel'//自定义打印模板
export default {
    name: "printPreview",
    props: {},
    data() {
        return {
            dictionary: [],//字典数据
            //获取源的值：字段名
            dictionaryContrast: {
                付款状态: 'PaymentState',
                结账类型: 'Check_out_flag',
                结账类型: "PaymentType",
                运输方式: 'Delivery_mode',
                发货状态: 'Logistics_status',
                安装状态: 'Install_status',
                税率: 'Tax_rate',
                一级仓库: 'WHSE_no',
                库位编码: 'WHSE_name',
                Sales_state: 'Sales_state',
                Install_service: 'Install_service',
                供应商客户: 'Supplier',
                无条件客户: 'Client',
                审核通过客户: 'Client',
                无条件客户: 'Client_name',
                audit: "AuditStatus",
                商品分类: "Item_clsno",
                生产调整单类型:"Type"
            },
            dictionaryKey: [
                "付款状态",
                "审核通过客户",
                "无条件客户",
                "供应商客户",
                "税率",
                "结账类型",
                "运输方式",
                "一级仓库",
                "Install_service",
                "发货状态",
                "Sales_state",
                "安装状态",
                "库位编码",
                "audit",
                "商品分类",
                "生产调整单类型"
            ],
            visible: false,
            spinning: true,
            waitShowPrinter: false,
            // 纸张宽 mm
            width: 0,
            // 模板
            template: {},
            // 数据
            printData: {
                headera: "XX信息表",
                // printDate: "",
                table: [
                ],
            },
            row: null,
        }
    },
    computed: {},
    watch: {
        "$route.query.TemplateID": {
            deep: true,
            immediate: true,
            handler(val) {
                // console.log(val) // 获取url上传递的参数
                this.TemplateID = val
                // this.getPrintTemplate(val)
            },
        },
        printData: {
            deep: true,
            handler(val) {
                this.getPrintTemplate(this.TemplateID)
            },
        },
    },
    async created() {

        // console.log(1, this.$route.query);
        await this.GetVueDictionary()
        this.getPrintData()

    },
    mounted() {
        // this.show({}, this.printData)
        // this.getPrintTemplate(this.TemplateID)

    },
    methods: {
        async getPrintTemplate(TemplateID) {
            let url = `api/q_print_options/getPageData`
            let params = {
                order: "desc",
                page: 1,
                rows: 30,
                sort: 'CreateDate',
                wheres: JSON.stringify([{ name: "ID", value: TemplateID, displayType: "text" }])
            }
            await this.http.post(url, params, "").then(reslut => {
                // console.log("reslut", reslut)
                if (reslut.total > 0) {
                    this.template = JSON.parse(reslut.rows[0].Template)
                    this.show({}, this.printData)
                } else {
                    this.base.ElMessageFn(reslut.message)
                }
            })
        },
        async getPrintData() {
            try {
                this.row = JSON.parse(this.$route.query.row)
               
                // console.log("this.row", this.row);
                // console.log("this.row.Produce_return", this.row.Produce_return);

                for (const key in this.row) {
                    this.dictionary.forEach(d => {
                        // console.log(" key11---", key, key == d.dicNo);
                        if (key == d.dicNo) {
                            // console.log("d-----------", d);
                            let valObj = d.data.filter(k => this.row[key] == k.key)
                            // console.log("valObj1-----------", valObj);
                            if (valObj.length) {
                                this.row[key] = valObj[0].value
                            }
                        }
                    })
                }
                  // 处理二维码
                  if(this.$route.query.QR&&JSON.parse(this.$route.query.QR)){
                    let lx = '';
                    console.log('this.$router')
                    console.log(this.$route.query.routeName)
                    console.log('this.$router')
                    if(this.$route.query.routeName == 'q_fittings_delivery'){
                        lx = 'YWFH'
                    }
                    if(this.$route.query.routeName == 'q_after_delivery'){
                        lx = 'SHFH'
                    }
                    if(this.$route.query.routeName == 'q_sales'){
                        lx = 'XSFH'
                    }
                    const url = 'api/q_print_options/GetPrintbq?lx='+lx+'&dh='+this.row.Voucher_sub
                    await this.http.get(url, "").then(reslut => {
                        console.log("二维码的请求",reslut)
                        this.printData= reslut
                    })
                    return;
                }
                // 处理二维码end
                this.printData = { ...this.row, ...this.printData }
                let urlDetail = `api/${this.$route.query.routeName}/getDetailPage` // 明细表请求数据地址
                let testID = this.$route.query.routeName.slice(2)
                testID = testID.charAt(0).toUpperCase() + testID.slice(1)
                // let ID = this.row.Stock_in
                let ID = this.row[testID]
                // console.log("ID", ID);
                let params = {
                    order: "desc",
                    page: "1",
                    rows: 100000,
                    sort: "Goods_sub",
                    value: ID,
                    wheres: "[]"
                }
                await this.http.post(urlDetail, params, "").then(reslut => {
                    // console.log("明细表数据", reslut)
                    if (reslut.total > 0) {
                        reslut.rows.forEach(item => {
                            for (const key in item) {
                                this.dictionary.forEach(d => {
                                    if (key == d.dicNo) {
                                        let valObj = d.data.filter(k => item[key] == k.key)
                                        if (valObj.length) {
                                            item[key] = valObj[0].value
                                        }
                                    }
                                })
                            }
                            // this.dictionary.forEach(x => {
                            //     console.log("item[x.dicNo]-----------", item[x.dicNo]);
                            //     if (item[x.dicNo] !== null) {
                            //         console.log("item[x.dicNo]", item[x.dicNo]);
                            //         console.log("x", x);
                            //         console.log("o", x.data.filter(o => o["key"] == item[x.dicNo]));
                            //         let o = x.data.filter(o => o["key"] == item[x.dicNo])
                            //         if (o.length > 0) {
                            //             console.log("oo", o[0].value);
                            //             item[x.dicNo] = o[0].value
                            //         }
                            //     }
                            // })
                        })
                        this.printData.table = reslut.rows
                    } else {
                        // this.base.ElMessageFn(reslut.message)
                    }
                })
            } catch (error) {
                console.error(error);
            }
        },
        hideModal() {
            this.visible = false
        },
        show(hiprintTemplate, printData, width = '210') {
            console.log("show");
            hiprintTemplate = new hiprint.PrintTemplate({
                // template: panel,
                template: this.template,
            })
            this.visible = true
            this.spinning = true
            this.width = hiprintTemplate.editingPanel ? hiprintTemplate.editingPanel.width : width;
            this.hiprintTemplate = hiprintTemplate
            // this.printData = printData
            printData.printDate = this.base.getDate(true)
            setTimeout(() => {

                // eslint-disable-next-line no-undef
                $('#preview_content_design').html(hiprintTemplate.getHtml(printData))
                this.spinning = false
            }, 500)
        },
        print() {
            try {
                this.waitShowPrinter = true
                this.printData.printDate = this.base.getDate(true)
                this.hiprintTemplate.print(this.printData, {}, {
                    callback: () => {
                        console.log('callback')
                        this.waitShowPrinter = false
                    }
                })
            } catch (error) {
                console.error(error);
            }
        },
        toPdf() {
            this.printData.printDate = this.base.getDate(true)
            this.hiprintTemplate.toPdf(this.printData, '打印预览');
        },
        //获取字典源
        async GetVueDictionary() {
            this.row = JSON.parse(this.$route.query.row)
            if (this.row.Produce_return || this.row.Produce_use) {
                this.dictionaryContrast = {
                    结账类型: 'Check_out_flag',
                    运输方式: 'Delivery_mode',
                    发货状态: 'Logistics_status',
                    生产状态: 'Production_state',
                    税率: 'Tax_rate',
                    生产工位: 'WHSE_no',
                    一级仓库: 'WHSE_jg',
                    库位编码: 'WHSE_name',
                    Sales_state: 'Sales_state',
                    Install_service: 'Install_service',
                    供应商客户: 'Supplier',
                    无条件客户: 'Client',
                    无条件客户: 'Client_name',
                    audit: "AuditStatus",
                    商品分类: "Item_clsno",
                    成本核算方式: "Cost_accounting",
                    生产调整单类型:"Type"
                }
                this.dictionaryKey = [
                    "无条件客户",
                    "供应商客户",
                    "税率",
                    "结账类型",
                    "运输方式",
                    "一级仓库",
                    "Install_service",
                    "发货状态",
                    "Sales_state",
                    "安装状态",
                    "库位编码",
                    "audit",
                    "商品分类",
                    "生产工位",
                    "成本核算方式",
                    "生产状态",
                    "生产调整单类型"
                ]
            }
            let url = `api/Sys_Dictionary/GetVueDictionary`
            await this.http.post(url, this.dictionaryKey, "").then(reslut => {
                // console.log("reslut", reslut)
                if (reslut.length > 0) {
                    for (const key in this.dictionaryContrast) {
                        reslut.forEach(item => {
                            if (item.dicNo == key) {
                                item.dicNo = this.dictionaryContrast[key]
                            }
                        });
                    }
                    this.dictionary = reslut
                    // console.log(" this.dictionary", this.dictionary)
                } else {
                    this.base.ElMessageFn(reslut)
                }
            })
        }
    }
}
// export default {
//     data() {
//         return {

//         }
//     },
//     created(){

//     },
//     methods: {
//         //浏览器打印
//         print() {
//             // 参数: 打印时设置 左偏移量，上偏移量
//             let options = { leftOffset: -1, topOffset: -1 };
//             // 扩展
//             let ext = {
//                 callback: () => {
//                     console.log("浏览器打印窗口已打开");
//                 },
//                 styleHandler: () => {
//                     // 重写 文本 打印样式
//                     return "<style>.hiprint-printElement-text{color:red !important;}</style>";
//                 },
//             };
//             // 调用浏览器打印
//             printData.printDate = currentTime()
//             hiprintTemplate.print(printData, options, ext);
//         }
//     }
// }
</script>
<style scoped lang="less">
.box {
    background-color: #f6f6f6;
    position: absolute;
    height: 100%;
    max-height: 100%;
    width: 100%;
    overflow: auto;
    text-align: center;
    box-sizing: border-box;
    padding: 10px;
}

#preview_content_design {
    // border-top: 1px solid #e8e8e8;
    display: flex;
    justify-content: center;
}

::v-deep .hiprint-printPaper {
    background-color: #fff !important;
}

.headerContent {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px 0 0 10px;

    // background-color: antiquewhite;
    .headerTitel {
        font-size: 20px;
        letter-spacing: 2px;
    }
}

::v-deep .ant-modal-body {
    padding: 0px;
}

::v-deep .ant-modal-content {
    margin-bottom: 24px;
}
</style>